import React, { useRef, useEffect, useState } from 'react';
import { Box, Typography, Grid, TextField, MenuItem, GlobalStyles } from '@mui/material';
import LocationOnIcon from '@mui/icons-material/LocationOn';
import { STATES, COUNTRIES } from './Constants';
import VerticalLabel from 'components/electrons/VerticalLabel';
import useVerticalLabel from 'components/electrons/useVerticalLabel';

const OwnerSection = ({ 
  formData, 
  handleChange, 
  errors, 
  textFieldStyle, 
  sectionHeaderStyle, 
  useSize,
  fullWidth = false // Added fullWidth prop with default false
}) => {
  const sectionRef = useRef(null);
  const fieldsRef = useRef({});
  
  // Initialize our vertical label hook
  const { activeLabel, isLabelVisible, getFieldProps } = useVerticalLabel();
  
  // Console log for debugging
  useEffect(() => {
    console.log('Vertical label is visible:', isLabelVisible);
    console.log('Active label:', activeLabel);
  }, [isLabelVisible, activeLabel]);

  // Register closest input detection by scroll position
  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          // When an input is near center viewport, add the special class
          const input = entry.target;
          if (entry.isIntersecting) {
            // Only apply to inputs not already focused
            if (!input.classList.contains('field-focused')) {
              input.classList.add('field-centered');
            }
          } else {
            input.classList.remove('field-centered');
          }
        });
      },
      {
        // This configures it to trigger when field is near center of viewport
        root: null, // viewport
        rootMargin: '-40% 0px -40% 0px', // narrow band in middle of screen
        threshold: 0.1 // trigger with minimal visibility
      }
    );

    // Register all input wrappers with the observer
    const wrappers = sectionRef.current?.querySelectorAll('.field-wrapper');
    if (wrappers) {
      wrappers.forEach((wrapper) => observer.observe(wrapper));
    }

    return () => observer.disconnect();
  }, []);

  // Event handlers to manipulate DOM directly (no state changes)
  const registerField = (name) => {
    return (ref) => {
      if (ref) {
        fieldsRef.current[name] = ref;
        
        // Clear all style classes
        const resetClasses = () => {
          // Get the wrapper element
          const wrapper = ref.closest('.field-wrapper');
          if (!wrapper) return;
          
          document.querySelectorAll('.field-wrapper').forEach(el => {
            // Remove focused class from all other wrappers
            if (el !== wrapper && el.classList.contains('field-focused')) {
              el.classList.remove('field-focused');
            }
          });
          
          // Add focused class to this wrapper
          wrapper.classList.add('field-focused');
          // Remove centered class (focus overrides centering)
          wrapper.classList.remove('field-centered');
        };
        
        // The actual focus handler
        const handleFocus = () => {
          resetClasses();
        };
        
        // The blur handler (only remove focused if not going to another field)
        const handleBlur = (e) => {
          // Don't remove the focused class if moving to another of our fields
          const relatedTarget = e.relatedTarget;
          const stillInFields = relatedTarget && 
            relatedTarget.closest && 
            relatedTarget.closest('.field-wrapper');
            
          if (!stillInFields) {
            ref.closest('.field-wrapper')?.classList.remove('field-focused');
          }
        };
        
        // Add the event listeners directly to the input element
        // Find the actual input element inside the MUI TextField
        const inputElement = ref.querySelector('input, select');
        if (inputElement) {
          // Remove existing listeners to prevent duplicates
          inputElement.removeEventListener('focus', handleFocus);
          inputElement.removeEventListener('blur', handleBlur);
          
          // Add fresh listeners
          inputElement.addEventListener('focus', handleFocus);
          inputElement.addEventListener('blur', handleBlur);
        }
      }
    };
  };

  return (
    <Box ref={sectionRef}>
      {/* Add the VerticalLabel component */}
      <VerticalLabel 
        label={activeLabel}
        isVisible={isLabelVisible}
        fontSize={2.5}
        color="primary.main"
      />
    
      {/* CSS-only approach using GlobalStyles */}
      <GlobalStyles styles={`
        /* Base field wrapper style */
        .field-wrapper {
          padding: 0;
          margin: 0;
          border-radius: 8px;
          transition: all 0.3s ease;
          box-shadow: none;
          width: 100%;
        }
        
        /* Field is in center of viewport */
        .field-wrapper.field-centered:not(.field-focused) {
          padding: 12px;
          margin: 8px 0;
          box-shadow: 0 4px 20px rgba(0,0,0,0.15);
          width: 100%;
        }
        
        /* Field has focus */
        .field-wrapper.field-focused {
          padding: 12px;
          margin: 8px 0;
          box-shadow: 0 4px 20px rgba(0,0,0,0.15);
          width: 100%;
        }
        
        /* Sizing for inputs in focused/centered fields */
        .field-wrapper.field-centered .MuiInputBase-root,
        .field-wrapper.field-focused .MuiInputBase-root {
          font-size: 1.1rem;
          padding: 4px 8px;
          width: 100%;
        }
        
        /* Background color for focused fields */
        .field-wrapper.field-focused .MuiInputBase-root {
          background-color: rgba(0,100,255,0.05);
        }
      `} />
      
      <Typography sx={sectionHeaderStyle}>
        <LocationOnIcon sx={{ fontSize: '1rem', verticalAlign: 'middle', mr: 0.5, color: 'primary.main' }} />
        Owner Address
      </Typography>
      
      <Grid 
        container 
        spacing={1}
        columns={12}
        sx={{ 
          width: '100%',
          margin: 0,
          padding: 0,
          display: 'flex',
          flexDirection: 'column'
        }}
      >
        <Grid item xs={12}>
          <Box className="field-wrapper" sx={{ width: '100%' }}>
            <TextField
              {... (fullWidth ? { fullWidth: true } : {})}
              label="Street Address"
              name="cBillAddress1"
              value={formData.cBillAddress1}
              onChange={handleChange}
              error={!!errors.cBillAddress1}
              helperText={errors.cBillAddress1}
              size={useSize}
              sx={textFieldStyle}
              ref={registerField('cBillAddress1')}
              required
              {...getFieldProps("Street Address")}
            />
          </Box>
        </Grid>
        <Grid item xs={12}>
          <Box className="field-wrapper" sx={{ width: '100%' }}>
            <TextField
              {... (fullWidth ? { fullWidth: true } : {})}
              label="Address Line 2"
              name="cBillAddress2"
              value={formData.cBillAddress2 || ''}
              onChange={handleChange}
              error={!!errors.cBillAddress2}
              helperText={errors.cBillAddress2}
              size={useSize}
              sx={textFieldStyle}
              ref={registerField('cBillAddress2')}
              {...getFieldProps("Address Line")}
            />
          </Box>
        </Grid>
        <Grid item xs={12}>
          <Box className="field-wrapper" sx={{ width: '100%' }}>
            <TextField
              {... (fullWidth ? { fullWidth: true } : {})}
              label="City"
              name="cBillCity"
              value={formData.cBillCity}
              onChange={handleChange}
              error={!!errors.cBillCity}
              helperText={errors.cBillCity}
              size={useSize}
              sx={textFieldStyle}
              ref={registerField('cBillCity')}
              required
              {...getFieldProps("City")}
            />
          </Box>
        </Grid>
        <Grid item xs={12}>
          <Box className="field-wrapper" sx={{ width: '100%' }}>
            <TextField
              {... (fullWidth ? { fullWidth: true } : {})}
              select
              label="State"
              name="cBillState"
              value={formData.cBillState}
              onChange={handleChange}
              error={!!errors.cBillState}
              helperText={errors.cBillState}
              size={useSize}
              sx={textFieldStyle}
              ref={registerField('cBillState')}
              required
              {...getFieldProps("State")}
            >
              {STATES.map((state) => (
                <MenuItem key={state} value={state}>
                  {state}
                </MenuItem>
              ))}
            </TextField>
          </Box>
        </Grid>
        <Grid item xs={12}>
          <Box className="field-wrapper" sx={{ width: '100%' }}>
            <TextField
              {... (fullWidth ? { fullWidth: true } : {})}
              label="ZIP Code"
              name="cBillZip"
              value={formData.cBillZip}
              onChange={handleChange}
              error={!!errors.cBillZip}
              helperText={errors.cBillZip}
              size={useSize}
              sx={textFieldStyle}
              ref={registerField('cBillZip')}
              required
              {...getFieldProps("ZIP Code")}
            />
          </Box>
        </Grid>
        <Grid item xs={12}>
          <Box className="field-wrapper" sx={{ width: '100%' }}>
            <TextField
              {... (fullWidth ? { fullWidth: true } : {})}
              label="County"
              name="bill_county"
              value={formData.bill_county || ''}
              onChange={handleChange}
              error={!!errors.bill_county}
              helperText={errors.bill_county}
              size={useSize}
              sx={textFieldStyle}
              ref={registerField('bill_county')}
              {...getFieldProps("County")}
            />
          </Box>
        </Grid>
        <Grid item xs={12}>
          <Box className="field-wrapper" sx={{ width: '100%' }}>
            <TextField
              {... (fullWidth ? { fullWidth: true } : {})}
              select
              label="Country"
              name="cBillCountry"
              value={formData.cBillCountry}
              onChange={handleChange}
              error={!!errors.cBillCountry}
              helperText={errors.cBillCountry}
              size={useSize}
              sx={textFieldStyle}
              ref={registerField('cBillCountry')}
              required
              {...getFieldProps("Country")}
            >
              {COUNTRIES.map((country) => (
                <MenuItem key={country} value={country}>
                  {country}
                </MenuItem>
              ))}
            </TextField>
          </Box>
        </Grid>
      </Grid>
    </Box>
  );
};

export default OwnerSection;